package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.context.BaseContext;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.mapper.DishFlavorMapper;
import com.sky.mapper.DishMapper;
import com.sky.result.PageResult;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * TODO
 *
 * @Author mr.Nuyoah
 * @Date2025/5/17 22:12
 */
@Service
public class DishServiceImpl implements DishService {



    @Autowired
    private DishMapper dishMapper;
    @Autowired
    private DishFlavorMapper dishFlavorMapper;
    /**
     * 新增菜品
     *
     * @param dishDTO
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveWithFlavor(DishDTO dishDTO) {
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish);
        /*dish.setCreateTime(LocalDateTime.now());
        dish.setUpdateTime(LocalDateTime.now());
        dish.setCreateUser(BaseContext.getCurrentId());
        dish.setUpdateUser(BaseContext.getCurrentId());*/
        //向菜品中添加一条数据
        dishMapper.insert(dish);

        //获取菜品id
        Long dishId = dish.getId();
        List<DishFlavor> flavors = dishDTO.getFlavors();
        if (flavors != null && flavors.size() > 0){
            flavors.forEach(d->{
                d.setDishId(dishId);
            });
            dishFlavorMapper.insertBatch(flavors);
        }
        String key = "dish:"+dish.getCategoryId();
        redisTemplate.delete(key);
    }

    /**
     * 分页查询菜品
     *
     * @param dto
     * @return
     */
    @Override
    public PageResult page(DishPageQueryDTO dto) {
        PageHelper.startPage(dto.getPage(), dto.getPageSize());
        List<Dish> list = dishMapper.page(dto);
        Page<Dish> page = (Page<Dish>) list;
        return new PageResult(page.getTotal(),page.getResult());
    }

    /**
     * 删除菜品
     *
     * @param ids
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteByIds(List<Long> ids) {
        //查询一下菜品表，看看售卖状态  ---dish
        for (Long id : ids) {
            Dish dish = dishMapper.getById(id);
            if(dish.getStatus().equals(StatusConstant.ENABLE)){
                //当前菜品在售状态，不能删除
                throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
            }
        }
        dishMapper.deleteByIds(ids);
        dishFlavorMapper.deleteByDishIds(ids);

        //清理缓存
        if(CollectionUtils.isNotEmpty(ids)){
            ids.stream().forEach(x -> {
                Dish dish = dishMapper.getById(x);
                String key = "dish:" + dish.getCategoryId();
                redisTemplate.delete(key);
            });
        }
    }

//    /**
//     * 根据id查询菜品
//     *
//     * @param id
//     * @return
//     */
//    @Override
//    public DishVO findById(Long id) {
//        // 根据id查询菜品表，获取菜品的基本信息
//        Dish dish = dishMapper.getById(id);
//
//        //根据菜品id查询口味表，获取口味数据
//        List<DishFlavor> dishFlavors =  dishFlavorMapper.getByDishId(id);
//
//        //将查询到的两部分数据封装到VO中
//        DishVO dishVO = new DishVO();
//        BeanUtils.copyProperties(dish, dishVO);
//        dishVO.setFlavors(dishFlavors);
//
//        return dishVO;
//    }
    /**
     * 根据id查询菜品和口味
     * @param id
     * @return
     */
    public DishVO getByIdWithFlavor(Long id) {
        // 根据id查询菜品表，获取菜品的基本信息
        Dish dish = dishMapper.getById(id);

        //根据菜品id查询口味表，获取口味数据
        List<DishFlavor> dishFlavors =  dishFlavorMapper.getByDishId(id);

        //将查询到的两部分数据封装到VO中
        DishVO dishVO = new DishVO();
        BeanUtils.copyProperties(dish, dishVO);
        dishVO.setFlavors(dishFlavors);

        return dishVO;
    }


    /**
     * 修改菜品
     *
     * @param dishDTO
     */
    @Override
    public void update(DishDTO dishDTO) {
        List<DishFlavor> flavors = dishDTO.getFlavors();
        if (flavors != null && flavors.size() > 0){
            dishFlavorMapper.deleteByDishId(dishDTO.getId());
        }
        List<DishFlavor> dtoFlavors = dishDTO.getFlavors();
        if (dtoFlavors != null && dtoFlavors.size() > 0){
            dtoFlavors.forEach(d->{
                d.setDishId(dishDTO.getId());
            });
            dishFlavorMapper.insertBatch(dtoFlavors);
        }
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish);
        dish.setUpdateTime(LocalDateTime.now());
        dish.setUpdateUser(BaseContext.getCurrentId());
        dishMapper.update(dish);

        //清理Redis缓存
        String key = "dish:"+dishDTO.getCategoryId();
        redisTemplate.delete(key);

    }

    /**
     * 更改状态
     *
     * @param status
     */
    @Override
    public void updateStatus(Integer status, Long id) {
        Dish dish = Dish.builder()
                .id(id)
                .status(status)
                .updateTime(LocalDateTime.now())
                .updateUser(BaseContext.getCurrentId())
                .build();
        dishMapper.update(dish);
        //清理缓存
        Dish dishDB = dishMapper.getById(id);
        String key = "dish:" + dishDB.getCategoryId();
        redisTemplate.delete(key);
    }

    /**
     * 根据分类id查询菜品
     * @param categoryId
     * @return
     */
    public List<Dish> list(Long categoryId) {
        Dish dish = Dish.builder()
                .categoryId(categoryId)
                .status(StatusConstant.ENABLE)
                .build();
        return dishMapper.list(dish);
    }

    @Autowired
    private StringRedisTemplate redisTemplate;
    /**
     * 条件查询菜品和口味
     *
     * @param dish
     * @return
     */
    @Override
    public List<DishVO> listWithFlavor(Dish dish) {
        String key = "dish:"+dish.getCategoryId();

        //1.查询缓存中的菜品列表
        ListOperations<String, String> opsForList = redisTemplate.opsForList();
        List<String> stringList = opsForList.range(key, 0, -1);
        if (CollectionUtils.isNotEmpty(stringList)){
            List<DishVO> dishVOList = stringList.stream()
                    .map(x -> JSON.parseArray(x, DishVO.class))
                    .flatMap(List::stream)
                    .collect(Collectors.toList());
            return dishVOList;
        }

        //2.如果缓存中没有则从数据库中查询
        List<Dish> dishList = dishMapper.list(dish);

        List<DishVO> dishVOList = new ArrayList<>();

        for (Dish d : dishList) {
            DishVO dishVO = new DishVO();
            BeanUtils.copyProperties(d,dishVO);

            //3.根据菜品id查询对应的口味
            List<DishFlavor> flavors = dishFlavorMapper.getByDishId(d.getId());

            dishVO.setFlavors(flavors);
            dishVOList.add(dishVO);
        }
        //4.将查询到的数据加入到Redis缓存中
        redisTemplate.opsForList().leftPushAll(key, JSON.toJSONString(dishVOList));
        return dishVOList;
    }
}
